package demo;

import bean.Student;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.List;

/**
 * 01-dom4j解析
 */
public class Demo01 {

    public static void main(String[] args) throws DocumentException {
        //②创建核心解析对象
        SAXReader saxReader = new SAXReader();
        //③读取xml文件，获取对应的文档对象
        Document document = saxReader.read("students.xml");
        //④获取根节点
        Element rootElement = document.getRootElement();
        //⑤解析根节点
        List<Element> studentEles = rootElement.elements("student");

        List<Student> studentList = new ArrayList<>();
        for (Element studentEle : studentEles) {
            String idStr = studentEle.attributeValue("id");
            Integer id = Integer.parseInt(idStr);
            System.out.println("id = " + id);
            String stuName = studentEle.elementText("stuName");

            System.out.println("stuName = " + stuName);
            String ageStr = studentEle.elementText("age");
            Integer age = Integer.parseInt(ageStr);

            System.out.println("age = " + age);
            String gender = studentEle.elementText("gender");

            System.out.println("gender = " + gender);

            Student student = new Student(id,stuName,gender,age);
            studentList.add(student);
        }

        //使用第一个student的id值
        System.out.println(studentList.get(0).getId());

        //使用第二个student的stuName值
        System.out.println(studentList.get(1).getStuName());

    }

}
